import {login,logout} from '@/network/admin'
import router from '../../router/index'
import { Message } from 'element-ui'


const getDefaultState = () => {
  return {
    token: localStorage.getItem("admin_TOKEN"),
    adminName:localStorage.getItem("admin_adminName"),
    list:[],
    //管理员侧边栏状态
    adminLevel:localStorage.getItem("admin_adminLevel"),
  }
}

const state = getDefaultState()

const mutations = {
  SET_USERNAME:(state,userName)=>{
    state.userName=userName
  },
  SET_BREAD:(state,list)=>{
    state.list=list
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_LEVEL: (state,adminLevel) => {
    state.adminLevel = adminLevel;
  },
}


const actions = {
  // user login
  login({ commit }, userInfo) {
    const {adminName, passWord,captcha} = userInfo
    return new Promise((resolve, reject) => {
      login({ adminName: adminName.trim(), password: passWord,captcha:captcha}).then(response => {
        const { data } = response
        if(data.code==100){
          commit('SET_TOKEN', data.data[1])
          commit('SET_LEVEL',data.data[0].level)
          commit('SET_USERNAME',adminName)

          localStorage.setItem("admin_adminName",adminName);
          localStorage.setItem("admin_TOKEN",data.data[1]);
          localStorage.setItem("admin_adminLevel",data.data[0].level);
          Message.success("登录成功!欢迎回来~")
          router.push({ path: this.redirect || '/admin/dashBoard' })
        }else{
          Message.warning(data.extend.msg)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },


  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then((res) => {
        // must remove  token  first
        localStorage.removeItem("admin_adminName");
        localStorage.removeItem("admin_TOKEN");
        localStorage.removeItem("admin_adminLevel");
        console.log(res);
        Message.success("账号已退出~")
        router.push("/login")
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

 setBreads({commit},list){
    return new Promise(resolve => {
      commit('SET_BREAD',list)
      resolve()
    })
 }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}

